package com.zyz.common.utils;


import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import java.io.UnsupportedEncodingException;

public class Mail {

    private JavaMailSender mailSender;

    private MailProperties mailProperties;

    public Mail(JavaMailSender mailSender, MailProperties mailProperties) {
        this.mailSender = mailSender;
        this.mailProperties = mailProperties;
    }

    public void sendMail(String to, String subject, String content) throws Exception {
        // 创建邮件信息
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,false);
        // 发件人邮箱和名称
        String from = mailProperties.getUsername();
        String personal = mailProperties.getProperties().get("nickname");
        personal = personal==null||personal.isEmpty() ? from : personal;
        helper.setFrom(from,personal);
        // 收件人邮箱
        helper.setTo(to);
        // 邮件标题
        helper.setSubject(subject);
        // 邮件正文，第二个参数表示是否是HTML正文
        helper.setText(content, true);

        // 发送邮件
        mailSender.send(mimeMessage);

    }
}
